import axios, {
  AxiosInstance,
  AxiosRequestConfig,
  InternalAxiosRequestConfig,
} from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { Session } from "@/utils/storage";
import qs from "qs";

// 配置新建一个 axios 实例
const request: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 50000,
  headers: { "Content-Type": "application/json" },
  paramsSerializer: {
    serialize(params) {
      return qs.stringify(params, { allowDots: true });
    },
  },
});

// 添加请求拦截器
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 在发送请求之前做些什么 token
    if (Session.get("token")) {
      config.headers.Authorization = `${Session.get("token")}`;
    }
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
request.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    const res = response.data;
    if (res.code && res.code !== 0) {
      // `token` 过期或者账号已在别处登录
      if (res.code === 401 || res.code === 4001) {
        Session.clear(); // 清除浏览器全部临时缓存
        window.location.href = "/"; // 去登录页
        ElMessageBox.alert("你已被登出，请重新登录", "提示", {})
          .then(() => {})
          .catch(() => {});
      }
      return Promise.reject(request.interceptors.response);
    } else {
      return response.data;
    }
  },
  (error) => {
    // 对响应错误做点什么
    if (error.message.indexOf("timeout") != -1) {
      ElMessage.error("网络超时");
    } else if (error.message == "Network Error") {
      ElMessage.error("网络连接错误");
    } else {
      if (error.response.data) ElMessage.error(error.response.statusText);
      else ElMessage.error("接口路径找不到");
    }
    return Promise.reject(error);
  }
);

// 封装请求方法
// get\post\put\delete\download\upload
function getAxios(url: string, params: any) {
  return request({
    url: url,
    method: "get",
    params: params,
  });
}
function postAxios(url: string, data: any) {
  return request({
    url: url,
    method: "post",
    data: data,
  });
}
function putAxios(url: string, data: any) {
  return request({
    url: url,
    method: "put",
    data: data,
  });
}
function deleteAxios(url: string, data: any) {
  return request({
    url: url,
    method: "delete",
    data: data,
  });
}
function downloadAxios(url: string, params: any) {
  return request({
    url,
    method: "get",
    responseType: "blob",
  }).then((res) => {
    const blob = new Blob([res.data]);
    const a = document.createElement("a");
    const urlObject = window.URL.createObjectURL(blob);
    a.href = urlObject;
    a.download = params.fileName || "下载文件";
    a.click();
    window.URL.revokeObjectURL(urlObject);
  });
}

export interface FileInfo {
  name: string;
  url: string;
}
/** 上传文件 （传入 FormData，上传进度回调） */
function uploadAxios(
  url: string,
  formData: FormData,
  onProgress?: (percent: number) => void
) {
  return request<any, FileInfo>({
    url: url,
    method: "post",
    data: formData,
    headers: { "Content-Type": "multipart/form-data" },
    onUploadProgress: (progressEvent) => {
      if (progressEvent.total) {
        const percent = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        );
        onProgress?.(percent);
      }
    },
  });
}

/** 上传文件（传入 File） */
function uploadAxiosFile(url: string, file: File) {
  const formData = new FormData();
  formData.append("file", file);
  return request<any, FileInfo>({
    url: url,
    method: "post",
    data: formData,
    headers: { "Content-Type": "multipart/form-data" },
  });
}
// 导出 axios 实例 service
// 导出其他封装的请求方法
export {
  request,
  getAxios,
  postAxios,
  putAxios,
  deleteAxios,
  downloadAxios,
  uploadAxios,
  uploadAxiosFile,
};
